// 认证相关工具函数
class AuthService {
    constructor() {
        this.token = localStorage.getItem('token');
        this.currentUser = null;
    }

    // 检查是否已登录
    isAuthenticated() {
        return !!this.token;
    }

    // 获取认证头
    getAuthHeaders() {
        if (!this.token) {
            throw new Error('未登录');
        }
        return {
            'Authorization': `Bearer ${this.token}`,
            'Content-Type': 'application/json'
        };
    }

    // 发送认证请求
    async authenticatedFetch(url, options = {}) {
        try {
            const response = await fetch(url, {
                ...options,
                headers: {
                    ...this.getAuthHeaders(),
                    ...options.headers
                }
            });

            if (response.status === 401) {
                // Token过期，跳转到登录页
                this.logout();
                window.location.href = '/';
                return;
            }

            return response;
        } catch (error) {
            console.error('认证请求失败:', error);
            throw error;
        }
    }

    // 获取当前用户信息
    async getCurrentUser() {
        if (this.currentUser) {
            return this.currentUser;
        }

        try {
            const response = await this.authenticatedFetch('/api/auth/me');
            if (response && response.ok) {
                this.currentUser = await response.json();
                return this.currentUser;
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
        }
        return null;
    }

    // 登出
    async logout() {
        try {
            // 调用后端logout API
            if (this.token) {
                await fetch('/api/auth/logout', {
                    method: 'POST',
                    headers: this.getAuthHeaders()
                });
            }
        } catch (error) {
            console.warn('调用后端logout API失败:', error);
            // 即使后端调用失败，也要继续清理本地数据
        } finally {
            // 清理本地存储
            localStorage.removeItem('token');
            localStorage.removeItem('remember');
            localStorage.removeItem('userInfo'); // 清理可能存在的用户信息缓存
            this.token = null;
            this.currentUser = null;
            
            // 显示退出成功消息
            this.showLogoutMessage();
        }
    }

    // 显示退出登录消息
    showLogoutMessage() {
        // 创建临时提示元素
        const message = document.createElement('div');
        message.innerHTML = `
            <div style="
                position: fixed;
                top: 20px;
                right: 20px;
                background: #27ae60;
                color: white;
                padding: 12px 20px;
                border-radius: 6px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                z-index: 10000;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                animation: slideIn 0.3s ease-out;
            ">
                ✅ 退出登录成功
            </div>
        `;
        
        // 添加动画样式
        if (!document.getElementById('logout-animation-style')) {
            const style = document.createElement('style');
            style.id = 'logout-animation-style';
            style.textContent = `
                @keyframes slideIn {
                    from { transform: translateX(100%); opacity: 0; }
                    to { transform: translateX(0); opacity: 1; }
                }
                @keyframes slideOut {
                    from { transform: translateX(0); opacity: 1; }
                    to { transform: translateX(100%); opacity: 0; }
                }
            `;
            document.head.appendChild(style);
        }
        
        document.body.appendChild(message);
        
        // 2秒后自动移除
        setTimeout(() => {
            message.firstElementChild.style.animation = 'slideOut 0.3s ease-in';
            setTimeout(() => {
                if (message.parentNode) {
                    message.parentNode.removeChild(message);
                }
            }, 300);
        }, 2000);
    }

    // 检查登录状态并重定向
    async checkAuthAndRedirect() {
        if (!this.isAuthenticated()) {
            window.location.href = '/';
            return false;
        }

        try {
            const user = await this.getCurrentUser();
            if (!user) {
                window.location.href = '/';
                return false;
            }
            return true;
        } catch (error) {
            window.location.href = '/';
            return false;
        }
    }
}

// 创建全局认证服务实例
const authService = new AuthService();

// 页面加载时检查认证状态
document.addEventListener('DOMContentLoaded', function() {
    // 如果在登录页面，且已经登录，则跳转到dashboard
    if (window.location.pathname === '/' && authService.isAuthenticated()) {
        window.location.href = '/dashboard';
        return;
    }

    // 如果在需要认证的页面，检查登录状态
    if (window.location.pathname !== '/') {
        authService.checkAuthAndRedirect();
    }
}); 